<template>
  <div>
    <el-dialog
      title="物模型"
      :visible.sync="modelDialogVisible"
      width="1000px"
      :close-on-click-modal="false"
      :append-to-body="true"
    >
      <el-tabs v-model="activeName" type="border-card" @tab-click="handleClick">
        <el-tab-pane label="功能列表" name="first">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <el-button
                size="small"
                style="margin-left: 15px"
                icon="el-icon-plus"
                @click="onAddThingModel"
              >
                新增
              </el-button>
            </div>
            <el-table
              :data="thingModelData"
              :header-cell-style="headerStyle"
              max-height="400px"
            >
              <el-table-column
                align="center"
                prop="type"
                label="功能类型"
              ></el-table-column>
              <el-table-column
                align="center"
                prop="name"
                label="功能名称"
              ></el-table-column>
              <el-table-column
                align="center"
                prop="description"
                label="描述"
              ></el-table-column>
              <el-table-column
                align="center"
                prop="unit"
                label="组织机构"
              ></el-table-column>
              <el-table-column
                align="center"
                prop="identifier"
                label="标识符"
              ></el-table-column>
              <el-table-column
                align="center"
                prop="dataType"
                label="数据类型"
              ></el-table-column>
              <el-table-column
                align="center"
                prop="dataRange"
                label="数据定义"
              ></el-table-column>
              <el-table-column align="center" prop="management" label="操作">
                <template slot-scope="scope">
                  <el-tooltip
                    class="item"
                    effect="dark"
                    content="编辑"
                    placement="bottom"
                  >
                    <i
                      @click="onEditThingModel(scope.row)"
                      class="iconfont tianxie tableBtnIcon"
                    ></i>
                  </el-tooltip>
                  <el-tooltip
                    class="item"
                    effect="dark"
                    content="删除"
                    placement="bottom"
                  >
                    <i
                      @click="onDelThingModel(scope.row)"
                      class="iconfont shanchu tableBtnIcon"
                    ></i>
                  </el-tooltip>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-tab-pane>
        <el-tab-pane label="型号配置" name="second">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <el-button
                size="small"
                style="margin-left: 15px"
                icon="el-icon-plus"
                @click="onAddModel"
              >
                新增
              </el-button>
            </div>
            <el-table
              :data="modelData"
              :header-cell-style="headerStyle"
              max-height="400px"
            >
              <el-table-column
                align="center"
                label="序号"
                type="index"
                width="80"
                height="30"
              ></el-table-column>
              <el-table-column
                align="center"
                prop="model"
                label="型号"
                min-width="120"
                show-overflow-tooltip
              ></el-table-column>
              <el-table-column
                align="center"
                prop="name"
                label="名称"
                show-overflow-tooltip
              ></el-table-column>
              <el-table-column
                align="center"
                prop="state"
                label="脚本状态"
                show-overflow-tooltip
              ></el-table-column>
              <el-table-column
                align="center"
                prop="modifyAt"
                label="修改时间"
                min-width="100"
                show-overflow-tooltip
              ></el-table-column>
              <el-table-column align="center" prop="management" label="操作">
                <template slot-scope="scope">
                  <el-tooltip
                    class="item"
                    effect="dark"
                    content="编辑"
                    placement="bottom"
                  >
                    <i
                      @click="onEditModel(scope.row)"
                      class="iconfont tianxie tableBtnIcon"
                    ></i>
                  </el-tooltip>
                  <el-tooltip
                    class="item"
                    effect="dark"
                    content="删除"
                    placement="bottom"
                  >
                    <i
                      @click="onDelModel(scope.row)"
                      class="iconfont shanchu tableBtnIcon"
                    ></i>
                  </el-tooltip>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
    <manageFunction
      ref="refManageFunction"
      :modelInfo="thingModelInfo"
      :editInfo="editInfo"
      :id="productInfo.id"
      :productKey="productInfo.productKey"
    ></manageFunction>
    <model
      ref="refModel"
      :type="type"
      :modelInfo="modelInfo"
      :productKey="productInfo.productKey"
    ></model>
  </div>
</template>

<script>
import tableStyleMixin from "@mixin/table-style";
import Pagination from "@components/Pagination.vue";
import {
  reqThingModelByProductKey,
  reqModels,
  reqModelDel,
  reqThingModelSave,
} from "@api/model";
import manageFunction from "./components/manageFunction.vue"; //新增
import model from "./components/model.vue"; //新增

export default {
  name: "",
  components: {
    Pagination,
    manageFunction,
    model,
  },
  mixins: [tableStyleMixin],
  props: ["productInfo"],
  data() {
    return {
      modelDialogVisible: false,
      activeName: "first",
      thingModelInfo: {},
      thingModelData: [],
      editInfo: {},

      // 型号配置
      modelData: [],

      type: "add",
      modelInfo: {},
    };
  },
  watch: {
    modelDialogVisible(val) {
      if (val) {
        this.onThingModel();
      }
    },
  },
  methods: {
    // 将后端数据转换为Element UI表格组件的数据格式
    formatDataForTable(model) {
      const formattedData = [];

      // 格式化属性数据
      model.properties.forEach((property) => {
        console.log(property.dataType.specs, "property.dataType.specs");
        formattedData.push({
          type: "Property",
          name: property.name,
          unit: property.unit || "",
          description: property.description || "",
          identifier: property.identifier,
          dataType: property.dataType.type,
          dataRange: `{${JSON.stringify(property.dataType.specs)}}`,
        });
      });

      // 格式化服务数据
      model.services.forEach((service) => {
        // 生成输入数据的字符串表示形式
        const inputs = service.inputData.reduce((acc, input) => {
          acc[`"${input.identifier}":"${input.dataType.specs.min}"`] = true; // 使用min作为示例，您可以根据需要使用max或其他值
          return acc;
        }, {});
        const inputsStr = `输入：{${Object.keys(inputs).join(", ")}}`; // 将对象转换为字符串

        // 生成输出数据的字符串表示形式
        const outputs = service.outputData.reduce((acc, output) => {
          acc[`"${output.identifier}":"${output.dataType.specs.min}"`] = true; // 同上
          return acc;
        }, {});
        const outputsStr = `输出：{${Object.keys(outputs).join(", ")}}`; // 将对象转换为字符串
        formattedData.push({
          type: "Service",
          name: service.name,
          identifier: service.identifier,
          unit: "",
          description: "",
          dataRange: `${inputsStr},${outputsStr}`,
        });
      });

      // 格式化事件数据
      model.events.forEach((event) => {
        // 生成输出数据的字符串表示形式
        const outputs = event.outputData.reduce((acc, output) => {
          acc[
            `"${output.dataType.specs.min}":"${output.dataType.specs.max}"`
          ] = true; // 同上
          return acc;
        }, {});
        const outputsStr = `{${Object.keys(outputs).join(", ")}}`; // 将对象转换为字符串
        formattedData.push({
          type: "Event",
          name: event.name,
          identifier: event.identifier,
          unit: "",
          description: "",
          dataRange: `{${outputsStr}}`,
        });
      });

      return formattedData;
    },

    // 表格
    handleClick(tab, event) {
      console.log(tab.paneName, "tab");
      this.activeName = tab.paneName;
      if (tab.paneName == "first") {
        this.onThingModel();
      } else if (tab.paneName == "second") {
        this.onModels();
      }
    },
    // 点击修改按钮
    async onEditThingModel(row) {
      // this.type = "edit";
      let { index, type } = this.onFilterSingle(row);
      console.log(
        JSON.stringify(this.thingModelInfo[type][index]),
        "JSON.stringify(this.thingModelInfo[type][index])"
      );
      this.editInfo = {
        index,
        type,
        data: JSON.parse(JSON.stringify(this.thingModelInfo[type][index])),
      };
      this.$refs.refManageFunction.functionDialogVisible = true;
    },

    // 删除物模型
    async onDelThingModel(row) {
      // 根据当条数据从列表的功能类型中找到对应的索引，然后删除、提交、刷新列表
      let { index, type } = this.onFilterSingle(row);
      this.thingModelInfo[type].splice(index, 1);
      const result = await this.$confirm(
        "此操作将永久删除该数据, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch(() => {});
      if (result !== "confirm") return;
      let res = await reqThingModelSave({
        requestId: this.productInfo.id,
        data: {
          productKey: this.productInfo.productKey,
          model: JSON.stringify(this.thingModelInfo),
        },
      });
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.$modal.notifySuccess("删除成功");
      this.onThingModel();
    },

    // 筛选功能类型数组里的具体某个索引
    onFilterSingle(row) {
      let index;
      let type;
      if (row.type == "Property") {
        index = this.thingModelInfo.properties.findIndex(
          (item) => item.identifier === row.identifier && item.name === row.name
        );
        type = "properties";
      } else if (row.type == "Service") {
        index = this.thingModelInfo.services.findIndex(
          (item) => item.identifier === row.identifier && item.name === row.name
        );
        type = "services";
      } else if (row.type == "Event") {
        index = this.thingModelInfo.events.findIndex(
          (item) => item.identifier === row.identifier && item.name === row.name
        );
        type = "events";
      }
      return {
        index,
        type,
      };
    },
    // 获取物模型
    async onThingModel() {
      let res = await reqThingModelByProductKey({
        requestId: this.productInfo.id,
        data: this.productInfo.productKey,
      });
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      let { data } = res.data;
      this.thingModelInfo =
        data && data.model && data.model != null ? data.model : {};
      if (data && data.model && data.model != null) {
        this.thingModelData = this.formatDataForTable(data.model);
      } else {
        this.thingModelData = [];
      }
    },
    // 新增
    onAddThingModel() {
      this.editInfo = {};
      this.$refs.refManageFunction.functionDialogVisible = true;
    },

    /**
     * @型号配置
     */
    onAddModel() {
      this.type = "add";
      this.modelInfo = {};
      this.$refs.refModel.modelDialogVisible = true;
    },
    onEditModel(row) {
      this.type = "edit";
      this.modelInfo = JSON.parse(JSON.stringify(row));
      this.$refs.refModel.modelDialogVisible = true;
    },
    async onDelModel(row) {
      const result = await this.$confirm(
        "此操作将永久删除该数据, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch(() => {});
      if (result !== "confirm") return;
      console.log(row);
      let res = await reqModelDel({
        data: row.id,
      });
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.$modal.notifySuccess("删除成功");
      this.onModels();
    },
    // 获取物模型
    async onModels() {
      let res = await reqModels({
        // requestId: this.productInfo.id,
        data: this.productInfo.productKey,
      });
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      let { list } = res.data;
      if (list.length) {
        list.forEach((item) => {
          // 将时间戳转换为Date对象
          var date = new Date(Number(item.modifyAt));
          // 获取年、月、日
          var year = date.getFullYear();
          var month = date.getMonth() + 1; // getMonth()返回的月份是从0开始的，所以需要+1
          var day = date.getDate();
          var hour = date.getHours();
          var minute = date.getMinutes();
          var second = date.getSeconds();

          // 将年、月、日转换为两位数的格式
          year = year.toString().padStart(4, "0");
          month = month.toString().padStart(2, "0");
          day = day.toString().padStart(2, "0");
          hour = hour.toString().padStart(2, "0");
          minute = minute.toString().padStart(2, "0");
          second = second.toString().padStart(2, "0");

          // 组合成年月日格式
          item.modifyAt = `${year}-${month}-${day} ${hour}:${minute}:${second}`;
        });
      }
      this.modelData = list;
    },
  },
};
</script>

<style scoped lang="less">
// @import url("~@views/style/tablePage.less");
@import url("../../../../common.less");
::v-deep .cell {
  display: flex;
  align-items: center;
  justify-content: space-around;
}
::v-deep .el-button--small {
  background: #7367f0;
  color: #fff;
  border: none;
}
.header {
  margin-bottom: 20px;
}
::v-deep .el-dialog__body {
  padding: 20px 20px 30px 20px !important;
}

.iconfont {
  cursor: pointer;
}

:v-deep .el-tabs__item {
  border: none !important;
}
</style>
